package pers.mtx.chatdemo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.java_websocket.client.WebSocketClient;

import android.util.Log;

import org.java_websocket.handshake.ServerHandshake;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

import pers.mtx.chatdemo.activity.SendActivity;
import pers.mtx.chatdemo.util.chat.model.get.ReceiveMsgVo;
import pers.mtx.chatdemo.util.chat.model.get.ReturnMsgVo;
import pers.mtx.chatdemo.util.chat.model.get.SendMsgVo;
import pers.mtx.chatdemo.util.chat.model.get.msg.FileMsgVo;
import pers.mtx.chatdemo.util.chat.model.get.msg.TextMsgVo;


public class WebSocketService extends Service {

    private WebSocketBinder wsBinder = new WebSocketBinder();


    public class WebSocketBinder extends Binder {
        public WebSocketService getService() {
            return WebSocketService.this;
        }
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return wsBinder;
    }

    @Override
    public void onCreate() {
        startSocket();
        super.onCreate();
    }

    private String TAG = "web_socket";
    private static WebSocketService instance = null;
    private static ObjectMapper mapper = new ObjectMapper();
    WebSocketClient client;
    //转成的要操作的数据
    URI uri;
    //后台连接的url
    String address = "ws://10.102.228.230:8889/ws";


    public static synchronized WebSocketService getInstance() {
        if (instance == null) {
            instance = new WebSocketService();
        }
        return instance;
    }

    public WebSocketService() {}

    public byte[] getFromAssets(String fileName) throws IOException {
        InputStream open = getAssets().open(fileName);
        byte[] bytes = new byte[open.available()];
        open.read(bytes);
//        InputStreamReader inputReader = new InputStreamReader(open);
//        BufferedReader bufReader = new BufferedReader(inputReader);
//        String line="";
//        StringBuilder Result= new StringBuilder();
//        while((line = bufReader.readLine()) != null)
//            Result.append(line);
        return bytes;
    }


    public void startSocket() {
        try {
            uri = new URI(address);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if (null == client || !client.isOpen()) {
            Log.d(TAG, "尝试建立: ");
            client = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    Log.d(TAG, "建立suc ");
                }

                @Override
                public void onMessage(String s) {
                    //后台返回的消息
                    Log.d(TAG, "返回: " + s);
                    try {
                        ReturnMsgVo msgVo = mapper.readValue(s.getBytes(StandardCharsets.UTF_8), ReturnMsgVo.class);
                        if (msgVo.getStatus().equals(ReturnMsgVo.RECEIVE_MSG)) {
                            ReceiveMsgVo receiveMsgVo = mapper.convertValue(msgVo.getMessage(), ReceiveMsgVo.class);
                            if (receiveMsgVo.getMsgType().equals(ReceiveMsgVo.TEXT)) {
                                TextMsgVo textMsgVo = mapper.convertValue(receiveMsgVo.getMessage(), TextMsgVo.class);
                                Intent setAction = new Intent().setAction(SendActivity.ACTION_GET_TEXT_MSG);
                                setAction.putExtra("data", textMsgVo.getMessage())
                                        .putExtra("senderId", textMsgVo.getSenderId())
                                        .putExtra("msgType", receiveMsgVo.getMsgType());
                                sendBroadcast(setAction);

                            }
                            if (receiveMsgVo.getMsgType().equals(ReceiveMsgVo.FILE)) {
                                FileMsgVo fileMsg = mapper.convertValue(receiveMsgVo.getMessage(), FileMsgVo.class);
                                Intent setAction = new Intent().setAction(SendActivity.ACTION_GET_TEXT_MSG);
                                setAction.putExtra("data", "文件名為"+fileMsg.getFileName()+"url為"+fileMsg.getUrl())
                                        .putExtra("senderId", fileMsg.getSenderId())
                                        .putExtra("msgType", receiveMsgVo.getMsgType());
                                sendBroadcast(setAction);
                            }
                        }
                        if (msgVo.getStatus().equals(ReturnMsgVo.SEND_SUCCESS)) {
                            SendMsgVo sendMsgVo = mapper.convertValue(msgVo.getMessage(), SendMsgVo.class);
                            Intent setAction = new Intent().setAction(SendActivity.ACTION_GET_TEXT_MSG);
                            setAction.putExtra("data", sendMsgVo.getChatId()+"发送成功")
                                    .putExtra("senderId", "本机")
                                    .putExtra("msgType", 1);
                            sendBroadcast(setAction);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {

                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                    Log.w(TAG, e.getMessage());
                }
            };
            client.connect();
        }
    }

    //向服务器发送消息
    public void sendMessage(Object s) {
        if (client == null || client.isClosed() || !client.isOpen()) {
            Log.d(TAG, "未建立实时通信");
            return;
        }
        try {
            Log.i(TAG, "发送: " + mapper.writeValueAsString(s));
            client.send(mapper.writeValueAsString(s));
        } catch (Exception e) {
            e.printStackTrace();
            startSocket();
        }
    }

    //关闭socket
    public void closeSocket() {
        if (client != null) {
            client.close();
            client = null;
        }
    }


}
